package com.darren.center.design.patterns.handler;

import com.darren.center.design.patterns.command.AbstractHandler;
import com.darren.center.design.patterns.dto.Context;
import com.darren.center.design.patterns.exceptions.ApiBizException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <h3>design-patterns</h3>
 * <p>接口权限</p>
 *
 * @author : Darren
 * @date : 2021年06月14日 19:56:37
 **/
@Component
public class InterfaceControlHandler extends AbstractHandler {

    private static Logger logger = LoggerFactory.getLogger(InterfaceControlHandler.class);
    private static final String SERVICECODE_MATCH_REGEX = "<serviceCode>([^<>]*)</serviceCode>";
    private static final String ID_MATCH_REGEX = "<partnerId>([^<>]*)</partnerId>";
    public static final String CONTROL_KEY = "oservice_interface_control";
    public static final String CONTROL_PREFIX = "control_";


    @Override
    public void processHandler(String reqXml, Context context) {
        try {
            String serviceCode = getCode(reqXml, SERVICECODE_MATCH_REGEX);
            String partnerId = getCode(reqXml, ID_MATCH_REGEX);
        } catch (ApiBizException e) {
            logger.error("sequence:{}，: 验证不通过{}", context.getMsgSeq(), e);
            throw new ApiBizException(e.getCode(), e.getMsg());
        } catch (Exception e) {
            logger.error("sequence:{}，: 验证不通过,异常{}", context.getMsgSeq(), e);
            throw new ApiBizException(ApiBizException.DEFAULT_CODE, "未知异常,请重试");
        }
    }

    private String getCode(String reqXml, String reg) {
        Pattern pattern = Pattern.compile(reg);
        if (StringUtils.isBlank(reqXml))
            return null;
        Matcher m = pattern.matcher(reqXml);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

}

